package pers.qianyu.month_202011.date_20201121;

import java.util.*;

/**
 * 297. 二叉树的序列化与反序列化
 * https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
 *
 * @author mizzle rain
 * @date 2020-11-21 21:32
 */
public class Codec2 {
    public String serialize(TreeNode root) {
        if (root == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node == null) {
                sb.append("#,");
                continue;
            } else {
                sb.append(node.val).append(",");
            }
            q.add(node.left);
            q.add(node.right);
        }
        return sb.toString();
    }

    public TreeNode deserialize(String data) {
        if (data == null || data.length() == 0) {
            return null;
        }
        String[] arr = data.split(",");
        int index = 0;
        Queue<TreeNode> q = new LinkedList<>();
        TreeNode root = new TreeNode(Integer.parseInt(arr[index++]));
        q.add(root);
        while (!q.isEmpty()) {
            TreeNode node = q.poll();

            String s = arr[index++];
            if ("#".equals(s)) {
                node.left = null;
            } else {
                node.left = new TreeNode(Integer.parseInt(s));
                q.add(node.left);
            }

            s = arr[index++];
            if ("#".equals(s)) {
                node.right = null;
            } else {
                node.right = new TreeNode(Integer.parseInt(s));
                q.add(node.right);
            }
        }
        return root;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(null);
        q.add(null);
        System.out.println(q);
    }
}
